package com.example.demo.controller;

import com.alipay.sofa.common.utils.StringUtil;
import com.example.demo.model.entity.User;
import com.example.demo.model.enums.ResultCodeEnum;
import com.example.demo.model.request.user.UserLoginRequest;
import com.example.demo.model.request.user.UserRegisterRequest;
import com.example.demo.model.request.user.UserSetBlackRequest;
import com.example.demo.model.response.PageQueryUserResponse;
import com.example.demo.service.UserService;
import com.example.demo.util.PageInfo;
import com.example.demo.util.Result;
import com.example.demo.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody UserRegisterRequest request) {
        //参数判空校验
        if (null == request) {
            return ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, false);
        }
        if (StringUtil.isBlank(request.getUserName()) || StringUtil.isBlank(request.getPassword())) {
            return ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, false);
        }
        userService.register(request);
        return ResultGenerator.genSuccessResult(true);
    }

    @GetMapping("/login")
    public Result<User> login(UserLoginRequest request) {
        //参数判空校验
        if (StringUtil.isBlank(request.getUserName()) || StringUtil.isBlank(request.getPassword())) {
            return ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, false);
        }
        return ResultGenerator.genSuccessResult(userService.login(request));
    }

    @RequestMapping("/getUser")
    public User getUserById(@RequestParam Integer id) {
        User user = userService.selectById(id);
        return user;
    }

    @GetMapping("/pageQuery")
    public Result<PageQueryUserResponse> pageQuery(PageInfo pageInfo) {
        //参数校验
        if (pageInfo == null || pageInfo.getCurrent() < 0 || pageInfo.getPageSize() <= 0) {
            return ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, null);
        }
        return ResultGenerator.genSuccessResult(userService.pageQuery(pageInfo));
    }

    @PostMapping("/setBlack")
    public Result<Boolean> setBlack(@RequestBody UserSetBlackRequest request) {
        //参数校验
        if (null == request || null == request.getUserId()) {
            return ResultGenerator.genFreeResult(ResultCodeEnum.PARAM_ILEEGAL, null);
        }
        return ResultGenerator.genSuccessResult(userService.setBlack(request));
    }

    ;
}
